# Copyright (c) 2019 Presto Labs Pte. Ltd.
# Author: yuxuan

import datetime
import json

import numpy as np
import pandas as pd

from absl import app, flags

FLAGS = flags.FLAGS

flags.DEFINE_string('strategy_name', '', '')
flags.DEFINE_string('start', '', '')
flags.DEFINE_string('end', '', '')


def get_agg_fill_ratio_from_fillinfo(strategy_name, start, end):
  df = pd.read_csv('fills.csv', error_bad_lines=False)
  df['dt'] = pd.to_datetime(df['timestamp'])
  df['order_side'] = np.where(df['order_side'].str.contains('BUY'), 'BUY', 'SELL')
  df = df.loc[df['strategy_name'] == strategy_name]
  df = df.loc[(start <= df['dt']) & (df['dt'] <= end)]
  agg_submit_qty = 0
  agg_fill_qty = 0
  data = dict()
  for symbol, sdf in df.groupby('symbol'):
    data[symbol] = dict()
    for order_side, odf in sdf.groupby('order_side'):
      last_agg_submit_ts = 0
      tw_agg_submit_qty = 0
      tw_agg_fill_qty = 0
      for _, row in odf.iterrows():
        ts = int(row['timestamp'])
        qty = float(row['fill_qty'])
        if ts - last_agg_submit_ts > 5e9:
          tw_agg_submit_qty = tw_agg_fill_qty = 0
        if row['action'].lower() == 'agg submitted':
          tw_agg_submit_qty += qty
          agg_submit_qty += qty
          last_agg_submit_ts = ts
        elif row['action'].lower() == 'filled':
          if tw_agg_fill_qty + qty < tw_agg_submit_qty + 1e-6:
            tw_agg_fill_qty += qty
            agg_fill_qty += qty
      data[symbol][order_side] = [agg_submit_qty, agg_fill_qty]
  print(json.dumps(data))
  return data


def main(argv):
  strategy_name = FLAGS.strategy_name
  start = FLAGS.start
  end = FLAGS.end
  assert strategy_name
  assert start
  assert end
  start = datetime.datetime.strptime(start, '%Y%m%d')
  end = datetime.datetime.strptime(end, '%Y%m%d')
  agg_fill_ratio = get_agg_fill_ratio_from_fillinfo(strategy_name, start, end)


if __name__ == '__main__':
  app.run(main)
